
var path=require("path");
var uuid=require("../common/uuid");
var dai_models = require("./platform-models");

var logger,mw;
module.exports = function(opts){

	//console.log("usedai");

	if(mw) return mw
	var app_models = dai_models(opts);
	
	dai_route(opts.server);

	mw = function(app_module){
		app_module.dai = app_models.build(app_module);
	};
	return mw;
};

var dai_route = function(server){
	//查询
	server.get("/dai/query/:model_name",doQuery);
	//查询单个
	server.get("/dai/get/:model_name/:model_id",doGet);
	//删除
	server.get("/dai/remove/:model_name",doRemove);
	//添加
	server.post("/dai/add/:model_name",doAdd);
	//批量添加
	server.post("/dai/addbatch/:model_name",doAddBatch);
	//更新
	server.post("/dai/update/:model_name",doUpdate);
	//自定义
	server.post("/dai/action/:action_name/:model_name",doAction);
};

/*查询*/
var doQuery = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M) {
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	var q = req.query;

	if(M._trigger && M._trigger["on_query"]){
		var rs = M._trigger["on_query"](q,req,res);
		if(rs){
			res.json(rs);
			return ;
		}
	}

	var $query = M.find({});

	var orders = {};
	if(q["_ordera"]){
		orders[q["_ordera"]] = 1;
		delete q["_ordera"];
		$query.sort(orders);
	}else if(q["_orderd"]){
		orders[q["_orderd"]] = -1;
		delete q["_orderd"];
		$query.sort(orders);
	}

	var page = q["_page"] || 0;
	var size = q["_size"] || 10;
	if(page){
		$query.skip(parseInt(page)*size);
	}	
	$query.limit(size);

	for(var p in q){
        if(p.indexOf("_") == 0){
            delete q[p];
        }
    }

	$query.find(q,function(err,list){
		if(!err && list){
			res.json({
				code : 1,
				list : list
			});
		}else{
			if(err){
				App.logger.info("query model ",req.params["model_name"],"error:");
				App.logger.info(q);
				App.logger.error(err);				
			}
			res.json({
				code : -5,
				messge : "error",
				list : []
			});
		}
	})

}

/*获取单个对象*/
var doGet = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M) {
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	M.findOne({id:req.params["model_id"]},function(err,data){
		if(!err && data){
			res.json({
				code : 1,
				data : data
			});
		}else{
			if(err){
				console.log("query model ",req.params["model_name"],"error:");	
				console.dir(err);		
			}
			res.json({
				code : -5,
				messge : "error",
				data : null
			});
		}
	});
}

/*删除*/
var doRemove = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M) {
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	/*
	if(M._trigger && M._trigger["on_remove"]){
		var rs = M._trigger["on_remove"](req.query,req,res);
		if(rs){
			res.json(rs);
			return ;
		}
	}*/

	M.remove(req.query,function(err){
		if(!err){
			res.json({
				code : 1,
				message : "ok",
				data : null
			});
		}else{
			if(err){
				console.log("remove model ",req.params["model_name"],"error:");
				//console.dir(req.query);	
				console.dir(err);	
			}
			res.json({
				code : -5,
				messge : "error",
				data : null
			});
		}
	});
}

function saveOne(M,data,callback){
	data.ctime = new Date();
	data.utime = new Date();
	data.id = App.uuid.createShortId();
	var m = new M(data);
	

	m.save(function(err){
		if(!err){
			callback({
				code : 1,
				message : "ok",
				data : m.toJSON()
			});
		}else{
			if(err){
				console.log("add model ",req.params["model_name"],"error:");
				console.dir(req.query);	
				console.dir(err);		
			}
			callback({
				code : -5,
				messge : "error",
				data : null
			});
		}
	});
}
    

/*添加*/
var doAddBatch = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);    
	if(!M) {
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

    var datas = req.body["datas"];
    //console.log(datas);
    datas = JSON.parse(datas);
    //console.dir(datas);
    var drs = [];
    for(var i=0;i<datas.length;i++){
        var data = datas[i];
		/*		
        if(M._trigger && M._trigger["on_add"]){
            var rs = M._trigger["on_add"](data,req,res);
            if(rs){
                res.json(rs);
                return ;
            }
        }*/
        saveOne(M,data,function(rs){
            if(rs.code < 0){
                res.json(rs);
                return ;
            }
            drs.push(rs);

            if(drs.length == datas.length){
                res.json({
                    code : 1,
                    list : drs
                });
            }
            
        });
    } 

}


/*添加*/
var doAdd = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M) {
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	req.body.ctime = new Date();
	req.body.utime = new Date();
	req.body.id = uuid.createShortId();
	var m = new M(req.body);

	/*
	if(M._trigger && M._trigger["on_add"]){
		var rs = M._trigger["on_add"](m,req,res);
		if(rs){
			res.json(rs);
			return ;
		}
	}*/

	M.emit("add",{
		doc:m
	});

	m.save(function(err){
		if(!err){
			res.json({
				code : 1,
				message : "ok",
				data : m.toJSON()
			});
		}else{
			M.emit("added",{
				doc:m
			});
			
			if(err){
				console.log("add model ",req.params["model_name"],"error:");
				console.dir(req.query);	
				console.dir(err);		
			}
			res.json({
				code : -5,
				messge : "error",
				data : null
			});
		}
	});

}

/*更新*/
var doUpdate = function(req,res){
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M){
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	req.body.utime = new Date();

	/*
	if(M._trigger && M._trigger["on_update"]){
		var rs = M._trigger["on_update"](req.body,req,res);
		if(rs){
			res.json(rs);
			return ;
		}
	}*/

	M.update(req.query,{$set:req.body},function(err){
		if(!err){
			res.json({
				code : 1,
				message : "ok",
				data : null
			});
		}else{

			M.emit("update",{
				query:req.query,
				body:req.body
			});

			if(err){
				console.log("update model ",req.params["model_name"],"error:");
				console.dir(req.query);	
				console.dir(err);	
			}
			res.json({
				code : -5,
				messge : "error",
				data : null
			});
		}
	});
}

/*自定义*/
var doAction = function(req,res){
	//console.log(req.params["model_name"]);
	var M = dai_models.getModel(req.params["model_name"]);
	if(!M){
		res.json({
			code : -4,
			message : "Invalid model name"
		});
		return ;
	}

	var action_name = req.params["action_name"];
	M.emit_action(action_name,{data:req.body,req:req,res:res},function(data){
		res.json(data);
	});

}